package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	interceptor "grpcinterceptor/proto"
	"grpcinterceptor/services"
	"log"
	"net"
)

func main() {
	rpcService := grpc.NewServer(grpc.UnaryInterceptor(unaryServerInterceptorFirst),
		grpc.StreamInterceptor(streamServerInterceptorFirst))

	interceptor.RegisterSayHiServiceServer(rpcService, new(services.SayHiService))

	lis, err := net.Listen("tcp", "localhost:11088")
	if err != nil {
		log.Fatalf("net listen err: %v", err)
	}

 	err = rpcService.Serve(lis)
 	if err != nil {
 		log.Fatalf("serve err: %v", err)
	}
}

// type UnaryServerInterceptor func(ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler) (resp interface{}, err error)
func unaryServerInterceptorFirst(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
	fmt.Println("unaryServerInterceptor -- 01 before handler")
	resp, err := handler(ctx, req)

	fmt.Println("unaryServerInterceptor -- 01 after handler")

	return resp, err
}

// type StreamServerInterceptor func(srv interface{}, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error
func streamServerInterceptorFirst(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
	fmt.Println("streamServerInterceptor -- 01 before handler")

	err := handler(srv, ss)

	fmt.Println("streamServerInterceptor -- 01 after handler")

	return err
}